<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import classification from '../../api/classification'
import { status, StateProtect } from '../../utils/classificationType'
import uploadImg from '../uploadImg.vue'
import era from '../utils/era.vue'
import collection from '../../api/collection'
import utils from '../../utils/utils'
import { useEraStore } from '../../store/era'
import { useImgStore } from '../../store/img'
import UploadImg from '../../api/uploadImg'
import provenanceSource from './provenanceSource.vue'
import { collectionAddDetail } from '../../utils/trueType'
import { useProvenceSourceStore } from '../../store/provenanceSourceDialog'
const eraStore = useEraStore()
const imgStore = useImgStore()
const provenceSourceStore = useProvenceSourceStore()
const valueSelectClassification = ref('')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<collectionAddDetail>({
    id: null,
    internalId: '',
    name: '',
    alternateName: '',
    classificationId: null,
    eraId: null,
    description: '',
    preservationStatus: '',
    weight: null,
    currentLocation: '',
    status: '',
    createdAt: null,
    img: '',
})
const validateClassification = (rule: any, value: any, callback: any) => {
  if (value===null) {
    callback(new Error('请选择分类'))
  } else {
    callback()
  }
}
const rules: FormRules = {
    name: [
        { required: true, message: '请输入藏品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符之间', trigger: 'blur' }
    ],
    /*internalId: [
        { required: true, message: '请输入藏品编号', trigger: 'blur' },
        { pattern: /^MUSEUM-\d{4}-\d{3}$/, message: '编号格式应为MUSEUM-年份-序号，如MUSEUM-2023-001', trigger: 'blur' }
    ],*/
    
    preservationStatus: [
        { required: true, message: '请选择保存状态', trigger: 'change' }
    ],
    /*weight: [
        { required: true, message: '请输入重量', trigger: 'blur' },
        { type: 'number', message: '重量必须为数字', trigger: 'blur' },
        { min: 0, message: '重量不能为负数', trigger: 'blur' }
    ],*/
    alternateName: [
        { max: 100, message: '别名长度不能超过100个字符', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择当前状态', trigger: 'change' }
    ],
    /*
    eraId: [
        { required: true, message: '请选择藏品年代', trigger: 'change' }
    ],*/
    currentLocation: [
        { required: true, message: '请输入存放位置', trigger: 'blur' },
        { max: 500, message: '存放位置描述不能超过500个字符', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入藏品描述', trigger: 'blur' },
        { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
    ]
}
const Classification = ref<any[]>([])
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            ruleForm.eraId = Number(eraStore.value)
            if (imgStore.imgRow) {
                // 先执行上传
                const response = await UploadImg.uploadImg(imgStore.imgRow)
                if (response.data.code === 200) {
                    // 先设置数据再关闭对话框
                    ruleForm.img = response.data.data
                    imgStore.setImgRowNull()
                }
            }
            //ruleForm.id = 0
            ruleForm.createdAt=utils.getCurrentTime()
            await classification.getSpecifiaId(valueSelectClassification.value).then((res) => {
                ruleForm.classificationId = res.data.data
            })
            provenceSourceStore.data.acquisitionDate=utils.changeTime(provenceSourceStore.data.acquisitionDate)   
            await collection.addCollection(ruleForm,provenceSourceStore.data).then((res) => {
                if (res.data.code === 200) {
                    utils.showMessage('新增藏品成功', 'success', 2000)
                } else {
                    utils.showMessage('新增藏品失败', 'error', 2000)
                }
            }) 
            formEl.resetFields()
            imgStore.imgUrl=''
            valueSelectClassification.value=''
        }
    })
}
onMounted(async () => {
    await classification.getClassification().then((res) => {
        Classification.value = res.data.data
    })
    console.log(ruleForm.classificationId)
})
</script>
<template>
    <div class="main-container">
        <el-card class="enhanced-card">
            <template #header>
                <div class="card-header">
                    <h2 class="form-title">新增藏品</h2>
                </div>
            </template>
            <el-form ref="ruleFormRef" class="enhanced-form" :model="ruleForm" :rules="rules" label-width="120px">
                <el-row :gutter="30">
                    <!-- 左列 -->
                    <el-col :span="12">
                        <el-form-item label="藏品名称：" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请输入完整藏品名称" clearable class="custom-input" />
                        </el-form-item>

                        <el-form-item label="藏品编号：" prop="internalId">
                            <el-input v-model="ruleForm.internalId" placeholder="例：MUSEUM-2023-001" clearable
                                class="custom-input" />
                        </el-form-item>

                        <el-form-item label="分类选择：" prop="classificationId">
                            <el-tree-select v-model="valueSelectClassification" :data="Classification"
                                placeholder="请选择分类" check-strictly class="full-width" clearable />
                        </el-form-item>

                        <el-form-item label="保存状态：" prop="preservationStatus">
                            <el-tree-select v-model="ruleForm.preservationStatus" :data="StateProtect.StateProtect"
                                placeholder="请选择保存状态" class="full-width" clearable />
                        </el-form-item>
                        <el-form-item label="重量(kg)：" prop="weight">
                            <el-input v-model="ruleForm.weight" placeholder="请输入重量" clearable class="custom-input" />
                        </el-form-item>
                    </el-col>

                    <!-- 右列 -->
                    <el-col :span="12">
                        <el-form-item label="藏品别名：" prop="alternateName">
                            <el-input v-model="ruleForm.alternateName" placeholder="可输入多个别名，用逗号分隔" clearable
                                class="custom-input" />
                        </el-form-item>
                        <el-form-item label="当前状态：" prop="status">
                            <el-tree-select v-model="ruleForm.status" :data="status.State" placeholder="请选择藏品状态"
                                class="full-width" clearable />
                        </el-form-item>

                        <el-form-item label="藏品年代：" prop="eraId">
                            <era class="full-width" />
                        </el-form-item>
                        <el-form-item label="来源信息：">
                            <provenanceSource />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 底部通栏表单项 -->
                <el-form-item label="存放位置：" prop="currentLocation">
                    <el-input v-model="ruleForm.currentLocation" type="textarea" :rows="3" placeholder="请输入存放位置"
                        resize="none" show-word-limit maxlength="500"></el-input>
                </el-form-item>
                <el-form-item label="详细描述：" prop="description">
                    <el-input v-model="ruleForm.description" type="textarea" :rows="4"
                        placeholder="请输入详细藏品描述（材质、尺寸、历史背景等）" resize="none" show-word-limit maxlength="500" />
                </el-form-item>
                <div class="upload-section">
                    <h3 class="section-title">藏品图片上传</h3>
                    <uploadImg />
                    <p class="upload-tips">支持JPG/PNG格式</p>
                </div>

                <div class="form-actions">
                    <el-button type="primary" size="large" class="submit-btn"
                        @click="submitForm(ruleFormRef)">提交信息</el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<style scoped>
.main-container {
    padding: 24px;
    background: #f5f7fa;
    min-height: 100vh;
    display: flex;
    justify-content: center;
}

.enhanced-card {
    width: 100%;
    max-width: 1200px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    :deep(.el-card__header) {
        background: linear-gradient(135deg, #409eff, #337ecc);
        border-radius: 12px 12px 0 0;
        padding: 20px;
    }
}

.form-title {
    color: orange;
    margin: 0;
    font-size: 1.5rem;
    font-weight: 600;
}

.enhanced-form {
    padding: 24px;

    .el-row {
        margin-bottom: 20px;
    }
}

.custom-input {
    :deep(.el-input__inner) {
        border-radius: 8px;
        padding: 12px 15px;
        transition: all 0.3s ease;

        &:hover {
            border-color: #409eff;
        }

        &:focus {
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
    }
}

.full-width {
    width: 100%;
}

.upload-section {
    margin: 30px 0;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px dashed #dcdfe6;

    .section-title {
        color: #606266;
        margin: 0 0 15px 0;
        font-size: 1.1rem;
    }

    .upload-tips {
        color: #909399;
        font-size: 0.9rem;
        margin: 10px 0 0;
    }
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;

    .submit-btn {
        padding: 12px 28px;
        border-radius: 8px;
        background: #409eff;
        transition: all 0.3s ease;

        &:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }
    }

    .cancel-btn {
        padding: 12px 28px;
        border-radius: 8px;
        border-color: #dcdfe6;

        &:hover {
            color: #409eff;
            border-color: #409eff;
        }
    }
}


@media (max-width: 768px) {
    .el-col {
        flex: 0 0 100%;
        /* ✅ 正确设置弹性布局 */
        max-width: 100%;
        /* ✅ 设置最大宽度 */
    }

    /* 或者如果使用Element Plus栅格系统 */
    :deep(.el-col) {
        width: 100% !important;
    }
}
</style>